package com.woniuxy.system.util;

import cn.hutool.jwt.JWTUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 生成token的工具类
 */
public class TokenUtils {

    public static String createToken(Long managerId, String signature, Long time, TimeUnit timeUnit, HttpServletRequest request) {
        Map<String,Object> payload = new HashMap<>();
        payload.put("managerId",managerId);
        if (timeUnit == TimeUnit.MINUTES) {
            payload.put("exp", LocalDateTime.now().plusMinutes(time)
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        } else if (timeUnit == TimeUnit.DAYS) {
            payload.put("exp", LocalDateTime.now().plusDays(time)
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        payload.put("requestIp", getRequestIP(request));
        String token = JWTUtil.createToken(payload, signature.getBytes());
        return token;
    }

    public static String getRequestIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
